# vim: fdm=marker fmr={{{,}}} cms=#%s

import os
import socket
import time
import re

import misc
import errcode
import para

class error(Exception):
    pass

class errlog:
    def __init__(self, program, location):
#{{{
        self.program=program
        self.location=location
        self.sock=None

        if location:
            if location[:2] == '//':
                res=re.search(":", location)
                if not res:
                    raise error, errcode.RET_ERR_PARA
                try:
                    addr=location[2:]
                    key,value=addr.split(':')
                    self.host=key
                    self.port=int(value)
                    self.sock=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                except ValueError:
                    raise error, errcode.RET_ERR_PARA
                except (socket.gaierror,socket.error):
                    raise error, errcode.RET_ERR_CONNECT
            else:
                if os.path.exists(location):
                    if not os.path.isdir(location) or not os.access(location, os.R_OK|os.W_OK|os.X_OK):
                        raise error, errcode.RET_ERR_FILE_ACCESS
                else:
                    try:
                        os.mkdir(location, 0744)
                    except OSError:
                        raise error, errcode.RET_ERR_FILE_OPEN
#}}}

    def __del__(self):
#{{{
        if self.sock:
            self.sock.close()
#}}}

    def write(self, msg):
#{{{
        if self.sock:
            request=''
            request,size=para.put_item(request, 'LOG', self.program, msg)
            try:
                self.sock.sendto(request, (self.host, self.port))
            except socket.error:
                return error.RET_ERR_FILE_OPEN
        else:
            try:
                file=None
                try:
                    ts=time.strftime(misc.TIMESTAMP_DEFAULT_FMT, time.localtime())
                    file=open('%s/%s.%.8s' % (self.location, self.program, ts), 'a')
                    locale_ts=time.strftime(misc.TIMESTAMP_COMMON_FMT, time.localtime())
                    file.write(locale_ts+' -- '+msg+'\n')
                finally:
                    if file: file.close()
            except IOError: 
                return error.RET_ERR_FILE_OPEN
#}}}
